console.log(`欢迎来到 Electron 👋`);
import { app, BrowserWindow, Menu } from 'electron';
import Store from 'electron-store';
import path from 'path';
import { registerIpcHandlers } from './ICP';

const store = new Store();
const isLogin = store.get('token');
console.log('isLogin', isLogin);
const icon = path.join(__dirname, '../public/music.png');

let mainWindow: BrowserWindow | null;

const createWindow = () => {
	// 创建浏览器窗口
	mainWindow = new BrowserWindow({
		width: isLogin ? 1100 : 400,
		height: isLogin ? 750 : 500,
		// 隐藏默认标题栏
		frame: false,
		// 透明窗口（可选）
		transparent: false,
		icon: icon,
		resizable: false,
		maximizable: false,
		title: '音乐播放器',
		webPreferences: {
			contextIsolation: true, //  启用上下文隔离，提高安全性
			nodeIntegration: false,
			preload: path.join(__dirname, './preload.js'),
		},
	});
	// 去除窗口菜单
	Menu.setApplicationMenu(null);

	if (process.env.NODE_ENV !== 'production') {
		mainWindow.loadURL(process.env['VITE_DEV_SERVER_URL']!);
		//  单独打开开发者工具
		mainWindow.webContents.openDevTools({
			mode: 'detach',
		});
	} else {
		mainWindow.loadFile(path.join(__dirname, '../dist/index.html'));
	}
	mainWindow.on('maximize', () => {
		mainWindow?.webContents.send('window-maximized');
	});
	mainWindow.on('unmaximize', () => {
		mainWindow?.webContents.send('window-unmaximized');
	});
	// 右键菜单
	const contextMenu = Menu.buildFromTemplate([
		{
			label: '刷新',
			role: 'reload',
		},
	]);
	mainWindow.webContents.on('context-menu', (e, params) => {
		contextMenu.popup({
			window: mainWindow!,
			x: params.x,
			y: params.y,
		});
	});
};

//  当Electron应用准备好时执行
app.whenReady().then(() => {
	createWindow(); //  创建主窗口
	registerIpcHandlers();
	app.on('activate', () => {
		if (BrowserWindow.getAllWindows().length === 0) {
			createWindow();
		}
	});
});

//  监听所有窗口关闭事件
app.on('window-all-closed', () => {
	if (process.platform !== 'darwin') {
		app.quit();
	}
});